<?php
namespace app\model;

class Common{

    static function GetWxappScene($system,$theme,$config,$fans,$themeid){
        global $_P,$_G;
        //判断是否为检查员及省外客户
        $is_local_users = true;
        $local_users_tips = '';
        if ((DOMAIN0 == "17.yixuan.net" || DOMAIN0 == "18.yixuan.net") && intval($_P['fromuid'])==0 && (($config['province'] != '四川省' && $_G['address']['city'] == '成都市')
                || ($config['province'] != '广东省' && $_G['address']['province'] == '广东')
                || ($config['province'] != '上海' && $_G['address']['province'] == '上海'))) {

            $is_local_users = false;
            $local_users_tips .= $_G['address']['province'] .'功能被限制；';
        }
        if ((DOMAIN0 == "17.yixuan.net" || DOMAIN0 == "18.yixuan.net") && intval($_P['fromuid'])==0 && (($_G['address']['city'] == '成都市') || ($_G['address']['province'] == '广东') || ($_G['address']['province'] == '上海'))) {
            $is_local_users = false;
            $local_users_tips .= $_G['address']['province'] .'功能被限制；';
        }
        if (empty($_G['address']['province']) || !empty($_G['address']['province']) && strpos("a".$config['province'].'省', $_G['address']['province']) == false){
            $is_local_users = false;
            $local_users_tips .= $_G['address']['province'] .'不在活动地区；';
        }
        //演示案例
        if ($system['wxapp_demo']==1 ) {
            $is_local_users = false;
            $local_users_tips .= '演示案例；';
        }
        //不合法粉丝
        if (!empty($fans) && $fans['status']!=1){
            $local_users_tips .= '粉丝状态异常；';
        }

        //外地用户不获取手机号
        if ($config['getmobile']>0 && !$is_local_users) {
            $config['getavatar']=1;
            $config['getmobile']=0;
        }

        if ($config['getmobile']>0 && $fans['mobile']!='' || $theme['status']==2 || TIMESTAMP > $theme['endtime']) {
            $config['getmobile'] = 0;
        }
        $avatar_default = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
        if ($config['getavatar'] >0 && ($fans['avatar']!='' && $fans['avatar']!=$avatar_default && $fans['nickname']!='新用户' && $fans['nickname']!='微信用户')) {
            $config['getavatar'] = 0;
        }
        $private_deal_mode = isset($config['private_deal_mode'])?(bool)$config['private_deal_mode']:true;

        if ($system['auth_mp'] != -1 && !(DOMAIN0 == "17.yixuan.net" || DOMAIN0 == "18.yixuan.net")){
            if (strlen($system['s']['auth_server'])>5){
                $system['auth_server'] = $system['s']['auth_server'];
                $system['auth_mode'] = 1;
            }
        }
        $auth_mode = intval($system['auth_mode']);
        if ($system['wxapp_demo']==1 || $fans['status']==2){$auth_mode = 0;}

        if (!$is_local_users) {
            yxlog($local_users_tips,'非本地用户');
            $config['getavatar']=$config['getavatar']==0?0:1;
            $system['auth_server'] .= '&branch=1';
            $auth_mode = 0;//不在活动地区走正常添写模式
            $private_deal_mode = false;//不在活动地区隐私协义弹窗模式
        }

        $result['private_deal_mode']=$private_deal_mode;
        $result['private_refuse_quit']=false;
        $result['auth']= array(
            'mode'=> $auth_mode,  //0为小程序本身授权，1为借用H5授权，2为借用小程序授权
            'server'=> $system['auth_server'],
            'getavatar'=> $config['getavatar'],
            'getmobile'=> $config['getmobile'],
            'workerurl'=> $system['wxapp_worker']==1?createMobileUrl('x_index',array('themeid'=>$themeid),true):"",
        );
        return $result;
    }

    static function pay($system,$theme,$config,$record,$recordid,$themeid,$realfee){
        if ($record['status']==3){
            Userdata::addLog($themeid, $record['uid'], 8, '',$record['workerid'],$record['fromuid']);
        }else{
            Userdata::addLog($themeid, $record['uid'], 7, '',$record['workerid'],$record['fromuid']);
        }

        if ($system['ruanjian']==5 && $record['type']==20 ) {
            Bargain::apiCreateBargain($theme,$config,$themeid,$record['uid'],$record['id'],$system);

        }
        if ($system['ruanjian']==0 && $system['softstyle']==5 ) {
            if(!empty($record['address']) && $record['type']==0){
                db_query("UPDATE ".tablename(t_shengshi)." SET recordid = " . $recordid . " WHERE areaId =".$record['address']);
            }
        }
        //开启代理模式
        if ($system['selling_agent']==1) {
            if ($record['workerid']==$record['fromuid'] && $config['selling_agent_reg']==1 && TIMESTAMP < $config['selling_agent_endtime']){
                //若推荐人为员工，且开启了自动注册代理，则执行；
                $superior= $record['workerid'];
                $superior_info = Worker::getThemeWorkerByUid($superior,$themeid);
                $fans= db_find('SELECT * FROM ' . tablename(t_fans) . ' 
                WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $record['themeid'],':uid' => $record['uid']));

                //如果是员工则不可以注册为代理；
                $myworker = Worker::getThemeWorkerByUid($record['uid'],$themeid);
                if (empty($myworker) || $myworker['level']>3){
                    Worker::SaveAgentInfo($superior_info,$superior,$fans);
                }
            }
        }
        if ($system['qrlist']==1 ) {
            if ($config['qrlistmode']==0 || ($config['qrlistmode']==1 && $record['isfinish']==1)) {
                $sql = "SELECT * FROM " . tablename ( t_qrlist ) . " 
                    WHERE themeid = '{$themeid}' and state = 1 and usercount<qrnum ORDER BY displayorder asc, id asc ";
                $list = db_find ( $sql);
                if (!empty($list)) {
                    $qrliststate = db_query("UPDATE ".tablename(t_qrlist)." SET usercount = usercount+1 WHERE id =".$list['id']);
                    $recordstate = db_query("UPDATE ".tablename(t_record)." SET qrimgid = '". $list['id'] ."',qrimg ='" .$list['qrimg']."' WHERE id = ".$recordid );
                }
            }
        }

        //宝妈拼拼看更新成交记录
        if ($system['is_lz_game']==1){
            if (!empty($config['lz_game_img']) && !empty($config['five_themeid'])){
                $config2 = Theme::getConfig($config['five_themeid']);
                Koi::checkInFiveLtTime($config['five_themeid'],$record['uid'],$config2);
            }
            Game::addUserGameLifeFlag($themeid,$record['uid'],$record['fromuid'],'order');
        }

        //转盘抽奖增加抽奖次数及积分
        if ($system['islottery']==1 || $system['ispoints']==1){

            if ($config['first_buy_begintime'] < TIMESTAMP && $config['first_buy_endtime'] > TIMESTAMP ){
                Record::update($recordid,array('isfirstbuy'=>1));
            }
            //self_look 未报名 self_pay 自己下单 friend_look 好友到访 friend_pay 好友下单 share_moments 朋友圈 share_qun 群
            $fans = Fans::getById($record['uid'],$themeid);
            Points::changeLotteryOrPoints(1,'self_pay',false,$themeid,$system,$fans);

            if (!empty($record['fromuid']) && $record['fromuid'] != $record['uid']) {
                $avatar=$fans['avatar'];
                $fans = Fans::getById($record['fromuid'], $themeid);
                $fans['avatar'] = $avatar;
                Points::changeLotteryOrPoints(1, 'friend_pay', false, $themeid, $system, $fans);
            }
        }
        //抽奖报名后增加抽奖机会
        if ($system['fanpai']==1 && $config['fanpaigroupid']>0) {
            if ($config['fanpaibaoming'] > 0){
                $sql = "SELECT * FROM " . tablename ( t_fanpaijihui ) . " WHERE themeid= " . $themeid . " and  uid= " . $record['uid'] . " and type = 1";
                $jihuilist = db_select ( $sql );
                if (empty($jihuilist)){
                    $tempdata = array(
                        'themeid'   => $themeid,
                        'uniacid'   => $record['uniacid'],
                        'uid'       => $record['uid'],
                        'openid'    => $record['openid'],
                        'nickname'  => $record['nickname'],
                        'avatar'    => $record['avatar'],
                        'status'    => 0,
                        'type'    => 1,
                        'jihui'    => $config['fanpaibaoming'],
                        'addtime'   => TIMESTAMP,
                        'workerid' => $record['workerid'],
                    );
                    if ($system['hdget']==1 &&Fans::getuid_old($record['workerid'],$themeid)) {
                        $data['workerid_old']  = $record['workerid'];
                    }
                    $insertid = db_insert(t_fanpaijihui, $tempdata);
                    db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + " . $config['fanpaibaoming'] . " WHERE themeid = " . $themeid . " and uid = ".$record['uid'] ."");
                }
            }
            if ($config['fanpaiyaoqing'] > 0){
                if (!empty($record['fopenid']) && $record['fopenid'] != $record['openid']){

                    $pm = array(":themeid"=>$themeid,":openid"=>$record['fopenid']);
                    $member = db_find("SELECT * FROM ".tablename(t_fans)."
                            WHERE themeid = :themeid and openid = :openid",$pm);

                    $tempdata = array(
                        'themeid'   => $themeid,
                        'uniacid'   => $record['uniacid'],
                        'uid'       => $record['fromuid'],
                        'openid'    => $record['fopenid'],
                        'nickname'  => $member['nickname'],
                        'avatar'    => $member['avatar'],
                        'fromuid'   => $record['uid'],
                        'fopenid'   => $record['openid'],
                        'status'    => 0,
                        'type'      => 2,
                        'jihui'     => $config['fanpaiyaoqing'],
                        'addtime'   => TIMESTAMP,
                        'workerid'  => $record['workerid'],
                    );
                    if (!empty($record['uid_old'])) {
                        $tempdata['fromuid_old']=$record['uid_old'];
                        $tempdata['fopenid_old']=$record['openid_old'];
                        $tempdata['workerid_old']=$record['workerid_old'];
                    }
                    $insertid = db_insert(t_fanpaijihui, $tempdata);
                    db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + " . $config['fanpaiyaoqing'] . " WHERE themeid = " . $themeid . " and uid = ".$record['fromuid'] ."");
                }
            }
        }
        //领泽新宝箱  下单   支付回调判断
        if ($system['is_lz_chest'] && $record['fromuid'] && $record['uid'] && $record['fromuid']!=$record['uid']){
            try {
                //$from_uid 通过哪位好友的进入  给对应用户增加操作次数
                //$uid  当前用户
                //friend_order  好友下单
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/lingze/core/model.php');;
                LingzeModel::ApiAddOptionFlag($record['fromuid'],$record['uid'],$themeid,'friend_order');
            }catch (Exception $e){
                var_dump($e->getMessage());die();
            }

        }
        if (($config['get_mystery_boxes']==1 && $record['isfinish']=1) || $config['get_mystery_boxes']==2 || $config['get_mystery_boxes']==3){
            Fans::setClickOpenBox($record['uid'],$themeid);
        }
        if ($config['isicon']==3){
            Fans::setClickOpenBox($record['uid'],$themeid);
        }
        //九宫格抽奖下单增加抽奖机会
        if (self::getLotteryLimitTime($system,$config,$theme)){
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/lottery/core/model.php');
            //给自己增加
            $fans = Fans::getById($record['uid'],$themeid);
            \LotteryModel::apiAddChance('self_order',$fans,$themeid,$record['uid'],$config);
            //给好友增加
            $from_fans = Fans::getById($record['fromuid'],$themeid);
            \LotteryModel::apiAddChance('friend_order',$from_fans,$themeid,$record['uid'],$config);
        }

        //贝莱亲子支付回调
        if ($system['softstyle']==108){
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/beilai/core/model.php');
            $res = \BeilaiModel::payRollback($themeid,$record['uid'],$record['id']);
        }
        //        教培回调
        if ($system['softstyle']==109){
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/education/core/model.php');
            $res = \EducationModel::payRollback($themeid,$record['uid'],$record['id']);
        }
        //优惠券回调
        if ($system['yx_coupon']==1){
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/coupon/core/model.php');
            $res = \CouponModel::payRollback($themeid,$record['uid'],$record['id'],$config,$system);
            //获取所有可用的优惠券
            //预售判断支付后自动发放
            \CouponModel::userCanGetCouponInPresale($themeid,$fans['uid'],$system,$config,$record['workerid']);
        }

        //红包雨使用回调
        if ($system['redrain']==1){
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/redrain/core/model.php');
            //好友下单
            if ($record['fromuid'] && $record['fromuid']!=$record['uid']){
                $from_fans = Fans::getById($record['fromuid'],$themeid);
                \RedRainModel::apiInsertChance($themeid,$config,$from_fans,9,$record['uid']);
            }
            \RedRainModel::payCallback($themeid,$record['uid'],$record['id']);
        }
        //多选分类限购
        if ($config['shopstype'] == 8 && $config['form_five_qty']==1){
            //插入文本5 用户记录表
            $option = $record['option'];
            if ($option){
                $option_arr = explode(',',rtrim($option,','));
                foreach ($option_arr as $k => $v){
                    if ($v){
                        $data = ['order_id'=>$recordid,'form_item_id'=>$v,'user_id'=>$record['uid'],'themeid'=>$themeid];
                        $check_item = db_get(t_form_five_user_flag,['order_id'=>$recordid,'form_item_id'=>$v,'user_id'=>$record['uid'],'themeid'=>$themeid]);
                        if (!$check_item){
                            $insertid = db_insert(t_form_five_user_flag,$data);
                            yxlog('用户uid:'.$record['uid'],'多选分类限购');
                        }
                    }
                }
            }
        }
        //邀请礼使用回调
        self::tuannum_add($system,$record,$themeid,'支付成功');
    }

    /**
     * Desc: 邀请礼给用户添加礼品
     * User: mf
     * Time: 2023/11/1 16:36
     * @param $system
     * @param $record
     * @param $themeid
     */
    static function tuannum_add($system,$record,$themeid,$tips){
        if($system['invite_gift']==1){
            yxlog($record,'邀请礼给用户添加礼品');
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/gift/core/model.php');
            \GiftModel::authentication($themeid,$record['id']);
        }
    }
    /**
     * Desc: 邀请礼给用户减少礼品
     * User: mf
     * Time: 2023/11/1 16:36
     * @param $system
     * @param $record
     * @param $themeid
     */
    static function tuannum_subtract($system,$record,$themeid,$tips){
        if($system['invite_gift']==1){
            yxlog($record,'邀请礼给用户减少礼品');
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/gift/core/model.php');
            \GiftModel::refund($themeid,$record);
        }
    }

    static function refund($system,$theme,$config,$record,$themeid){
        //转盘抽奖增加抽奖次数及积分--退款
        if ($system['islottery']==1 || $system['ispoints']==1){
            //self_look 未报名 self_pay 自己下单 friend_look 好友到访 friend_pay 好友下单 share_moments 朋友圈 share_qun 群
            $fans = Fans::getById($record['uid'],$themeid);
            Points::changeLotteryOrPoints(2,'self_pay',false,$themeid,$system,$fans,$record['isfirstbuy']);

            if (!empty($record['fromuid']) && $record['fromuid'] != $record['uid']) {
                $avatar=$fans['avatar'];
                $fans = Fans::getById($record['fromuid'], $themeid);
                $fans['avatar'] = $avatar;
                Points::changeLotteryOrPoints(2, 'friend_pay', false, $themeid, $system, $fans,$record['isfirstbuy']);
            }
        }
        //邀请礼使用回调
        self::tuannum_subtract($system,$record,$themeid,'退款成功');
    }
    static function share($system,$theme,$config,$fans,$themeid,$type){
        $is_moments = false;
        if ($type ==0 || $type=='friend' ) { //好友
            Userdata::addLog($themeid, $fans['uid'], 2);
        }else{//朋友圈
            Userdata::addLog($themeid, $fans['uid'], 3);
            $is_moments = true;
        }
        //针对于小程序
        if ($type=='moments'){
            $is_moments = true;
        }
        //积分抽奖增加
        if ($system['islottery'] || $system['ispoints']){
            $op = isset($_P['op'])?$_P['op']:'';
            $op_type = isset($_P['op_type'])?$_P['op_type']:'';
            $new_user = isset($_P['new_user'])?$_P['new_user']:false;
            $lr_id = isset($_P['lr_id'])?$_P['lr_id']:0;
            //self_look 未报名 self_pay 自己下单 friend_look 好友到访 friend_pay 好友下单 share_moments 朋友圈 share_qun 群

            $key = getShareReceiveCode($op_type);
            if ($key){
                if ($lr_id){
                    //判断中奖记录id  更新对应的中奖记录的操作
                    $res = Lottery::getLastLtRecordInfoByUid($key,$lr_id);
                }else{
                    //判断用户最近是否有中奖记录  存在对应类型 未领取 时间倒序 最后一条
                    $res = Lottery::getLastLtRecordInfo($key,2,$fans['uid']);
                }
                if ($res){
                    $lr_id = $res['lr_id'];
                    $receive_remain_num = $res['receive_remain_num'];
                    $new_receive_remain_num = $receive_remain_num-1;
                    $new_receive_remain_num = $new_receive_remain_num<0?0:$new_receive_remain_num;
                    $data = [
                        'receive_remain_num'=>$new_receive_remain_num
                    ];
                    if ($new_receive_remain_num<=0){
                        $data['status'] = 1;
                    }
                    $result = db_update(t_receive,$data,['lr_id'=>$lr_id]);
                }
            }
//        $op = 2;
//        $op_type = 'friend_pay';
//        $new_user = false;
//        $is_bw = false;
            if ($op && $op_type && $themeid){
                $res = Points::changeLotteryOrPoints($op,$op_type,$new_user,$themeid,$system,$fans);
            }
        }
        //领泽新宝箱
        if ($system['is_lz_chest']){
            try {
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/lingze/core/model.php');;
                LingzeModel::ApiAddOptionFlag($fans['uid'],$fans['uid'],$themeid,'share');
            }catch (Exception $e){
                var_dump($e->getMessage());die();
            }
        }
        //九宫格抽奖分享朋友圈增加抽奖机会
        if ($is_moments && self::getLotteryLimitTime($system,$config,$theme)){
            yxlog('分享朋友圈进入抽奖调用','抽奖日志');
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/lottery/core/model.php');
            \LotteryModel::apiAddChance('share_moments',$fans,$themeid,$fans['uid'],$config);
        }
        //判断红包雨
        if ($system['redrain']>0){
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/redrain/core/model.php');
            //判断类型
            if ($type=='friend'){
                //分享好友
                \RedRainModel::apiInsertChance($themeid,$config,$fans,3,$fans['fromuid']);
            }elseif ($type=='moments'){
                //分享朋友圈
                \RedRainModel::apiInsertChance($themeid,$config,$fans,1,$fans['fromuid']);
            }
        }
    }
    /**
     * Desc:给from_uid用户增加记录  达到好友到访记录数增加抽奖机会
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/9/3 4:29 下午
     * @param $fans  //打开链接的用户
     * @param $from_uid  //判断增加机会的用户uid
     * @param $themeid   //活动id
     * @param $config    //配置信息
     */
    static function newfans($system, $theme, $config, $themeid, $status, $fans){
        global $_P,$_G;
        //阅读红包
        if($system['fenxiao05']==1 && $status==1){
            $r=Comm::readcomm($system,$themeid,$config);
        }
        //判断新粉丝
        if ($system['lottery']==1){
            if (self::getLotteryLimitTime($system,$config,$theme) && $config['yx_lt_friend_view']>0){
                $uid = $_G['member']['uid'];
                $from_uid = intval($_P['fromuid']);
                if ($fans['uid']==$from_uid || empty($from_uid)){
                    $from_uid =  Fans::get_now_formuid($themeid)['fromuid'];
                }
                yxlog(['uid'=>$uid,'fromuid'=>$from_uid],'进入抽奖判断新粉丝');
                if ($uid!=$from_uid && $from_uid){
                    
                    require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                    require_once get_path('plugin/lottery/core/model.php');
                    $from_fans = \LotteryModel::getUserInfoById($from_uid,$themeid);
                    $is_new_fans = \LotteryModel::checkNewUser($fans,$config);

                    if (!$is_new_fans){
                        Userdata::addLog($themeid, $from_uid, 17, '好友不是新粉丝，不增加机会',$fans['workerid'],$uid);
                    }
                    if ($from_fans && $is_new_fans){
                        //判断是否给上级增过机会记录
                        $has_friend_flag = \LotteryModel::getFriendViewChanceFlag($themeid,$from_fans['uid'],$uid);
                        if (!$has_friend_flag){
                            $is_can_add_firend_view_chance = true;
                            if ($config['yx_lt_view_user_type']){
                                $themyrecord = Record::getLastGroupByUid($from_uid,$themeid);
                                if (!$themyrecord){
                                    $is_can_add_firend_view_chance = false;
                                    Userdata::addLog($themeid, $from_uid, 17, '用户未支付，好友助力失败，不增加机会',$fans['workerid'],$uid);
                                }
                            }
                            if ($is_can_add_firend_view_chance){
                                Userdata::addLog($themeid, $from_uid, 17, '好友助力成功',$fans['workerid'],$uid);
                                \LotteryModel::apiAddChance('friend_view',$from_fans,$themeid,$uid,$config);
                            }
                        }else{
                            Userdata::addLog($themeid, $from_uid, 17, '好友已助力，不增加机会',$fans['workerid'],$uid);
                        }
                    }
                }
            }
        }

        Sms::CheckAndSendSms('friend_newfans',$system,$config,$themeid, $fans);
    }

    // $theMyRecord 当前用户的定单信息
    // $recordid 当前显示的定单ID
    static function index($system,$theme,$config,$fans,$theMyRecord,$recordid,$themeid,$workerid,$formuid){
        global $_P,$_G;
        $result = [];
        if (self::get_open_other_form($system,$config)) {
            $result["other_form"] = Otherform::getBaseInfoAndInput($system, $theme, $config, $fans);
        }
        if ($system['softstyle']==109){
            //调用贝莱首页基础信息
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/education/core/model.php');
            $education_res = \EducationModel::getEducationConfig();
            foreach ($education_res as $k => $v){
                $result[$k] = $v;
            }
        }
        //文本5多选分类
        if ($config['shopstype'] == 8 || $config['presale']['shopstype'] == 8){
            $tmp_arr = [];
            if ($config['dx_cate_only_data']){
                foreach ($config['dx_cate_only_data'] as $k => $v){
                    $item_can_show = Common::getFormFIveAndLimitBuyCanShowByItemId($config,$themeid,$v['id']);
                    if ($v['status']==1 && $item_can_show){
                        array_push($tmp_arr,$v);
                    }
                }
                $result['dx_cate_only_data'] = json_encode($tmp_arr);
            }
            if ($config['options']){
                $tmp_options = $config['options'];
                foreach ($tmp_options as $k => $v){
                    $tmp_list = $v['list'];
                    foreach ($tmp_list as $k1 => $v1){
                        $item_can_show = (int)Common::getFormFIveAndLimitBuyCanShowByItemId($config,$themeid,$v1['id']);
                        if (!$item_can_show || $item_can_show=='0' || $item_can_show==0){
                            $config['options'][$k]['list'][$k1]['status']=0;
                        }
                    }
                }
            }
            $result['options'] = $config['options'];
        }
//        抽奖判断
        if ($system['lottery']==1){
            
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/lottery/core/model.php');
            \LotteryModel::initInfo($themeid,$config,$fans['uid'],$formuid);
        }
        //汽车行业
        if ($config['car_order_list']){
            $car_order_list =Fans::getCarOrderList($themeid,$config,1);
            $result['car_order_list'] = [
                'total'=>$car_order_list['total'],
                'list'=>$car_order_list['list'],
            ];
        }
        //显示分享人
        if($config['show_fromuid_info']==1&&$formuid>0){
            $fromuid_sql  = "SELECT id,avatar,username,nickname FROM ".tablename (t_fans)." where uid={$formuid} and themeid = {$fans['themeid']}";
            $form_data = db_find($fromuid_sql);
            $result['fromuid_info'] = $form_data;
        }else{
            $result['fromuid_info'] = '';
        }
        if(($system['multiple_merchants_mobile']==2 || $system['multiple_merchants_mobile']==3) && $config['showshop']==0) {
            $result['shangjia_contact_detail'] = Fans::shangjia_contact_detail($system);
            $result['sj_contact_show_worker_qrcode'] = $system['multiple_merchants_mobile'];
        }
        if ($config['private_kfewm']==1){
            //底部专属客服二维码
            $result['private_kfewm'] = [
                'bg_img'=>$config['private_kfewm_bg_img'],
                'bg_color'=>$config['private_kfewm_bg_color'],
                'title'=>$config['private_kfewm_title'],
                'fontsize'=>$config['private_kfewm_fontsize'],
                'line_height'=>$config['private_kfewm_line_height'],
                'title_color'=>$config['private_kfewm_title_color'],
                'top'=>$config['private_kfewm_top'],
                'left'=>$config['private_kfewm_left'],
            ];
        }
//        默认手机号自有输入
        $result['mobile_input_type']=1;
        if ($config['mobile_input_type']==2 || ($config['form2']['mobile_input_type'] && $config['form2']['mobile_input_type']==2) || ($config['form3']['mobile_input_type'] && $config['form3']['mobile_input_type']==2)){
            $result['mobile_input_type']=2;
        }
        //短信更新发送状态
        $has_sms_config = [];
        if (db_tableexists(t_sms_config)){
            $has_sms_config = db_get(t_sms_config,['themeid'=>$themeid,'module_name'=>MODULE_NAME]);
        }
        if (($has_sms_config && $has_sms_config['open_yx_sms']==1) || ($config['open_yx_sms']==1)){
            Sms::reportSms($themeid);
        }
        //礼品
        if ($system['invite_gift']==1){
            $intive_gift_config = db_get(t_intive_gift_config,array('software'=>MODULE_NAME,'themeid'=>$themeid),array('show_mode'));
            $result['intive_gift_config_show_mode'] = $intive_gift_config['show_mode'];
        }
        //判断对接小程序自动发货
        if (DOMAIN0 == "17.yixuan.net" || DOMAIN0 == "18.yixuan.net" || DOMAIN0 == "5.yixuan.net"){
            AutoShipment::openIndexAfterShipment($system,$theme);
        }
        return $result;
    }

    static function getshareinfo($system,$theme,$config,$fans,$shopname,$workername,$recordid=0,$fromuid=0)
    {
        global $_P;
        $themeid= $theme['id'];
        if ($config['bargain_marketprice']>0 && !empty($fans['uid'])){
            //当前用户有发起砍价，则走支付的分享文字
            $recordid = Bargain::getUserRecordid($themeid,$fans['uid']);
            if (!empty($recordid)){
                $themyrecord = Record::getById($recordid);
                $themyrecord['status']=1;
            }
        }else{
            $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
        }

        $myworker = Worker::getThemeWorkerByOpenid($fans['openid'],$themeid,1);
        if (!$shopname){
            $shopname = $myworker['company'];
        }
        if (!$workername){
            $workername = $myworker['username'];
        }
        //分享jssdk
        if($themyrecord['status'] >= 1 && !empty($themyrecord)){
            if (!empty($config['sharetitlexcx2']) ){
                $sharetitlexcx = $config['sharetitlexcx2'];
            }else{
                $sharetitlexcx = $theme['title'];
            }
            $sharetitle = str_replace("NICK",$fans['nickname'],$sharetitlexcx);
            $sharetitle = str_replace("NAME",$themyrecord['username'],$sharetitle);
            $sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);

            if ($themyrecord['type']==1){
                $recordid = $themyrecord['pid'];
            }else{
                $recordid = $themyrecord['id'];
            }
            $workerid = $themyrecord['wokerid'];
        }else{
            if (!empty($config['sharetitlexcx'])){
                $sharetitlexcx = $config['sharetitlexcx'];
            }else{
                $sharetitlexcx = $theme['title'];
            }
            $sharetitle = str_replace("NICK",$fans['nickname'],$sharetitlexcx);
            $sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);
        }

        if (!empty($myworker) && $myworker['level']<=3) {
            $recordid = 0;
            $workerid = $myworker['wokerid'];
        }
        if (empty($workerid)) {
            if (!empty($_P['path'])){
                //如果有path路径则取path中的workerid;
                $relation = db_get(t_userdata_relation, array('id'=>$_P['path']));
            }else{
                $relation = Relation::getByThemeUid($themeid,$fans['uid']);
            }
            $workerid = $relation['workerid'];
        }

        if ($config['iswxshare']==1) {
            $theme['title'] = $sharetitle;
        }
        if ( $config['livedata']['yure']==1 && in_array($config['livedata']['livestatus'], array(101,102,105,106))) {
            if(!empty($config['livedata']['lname'])){
                $sharetitle=$config['livedata']['lname'];
            }
        }
        if (strpos($sharetitle, "WORKER") !== false){
            $sharetitle = str_replace("WORKER",$workername,$sharetitle);
        }elseif (!empty($workername) && $config['isshowkefu']==1){
            $sharetitle = $sharetitle ."【客服:".$workername."】";
        }

        if (empty($config['shareimgxcx'])){
            $shareimgurl = tomedia($config['headlogo']);
        }else{
            $shareimgurl = tomedia($config['shareimgxcx']);
        }

        if (!empty($fans['uid'])) {
            $fromuid = $fans['uid'];
        }
        $sharedata = array(
            'fromuid'=>$fromuid,
            'recordid'=>$recordid,
            'themeid'=>$themeid,
            'path'=>Userdata::MyPath($themeid,$workerid,$fans['uid'],$_P['path']),
        );
        if ($config['isicon']==3) {
            if (empty($themyrecord)){
                $sharedata['help_uid'] = $_P['fromuid'];
            }
        }

        $shareurl =  Theme::createwxAppUrl('pages/index/index',$sharedata);

        $shareinfo['sharetitle'] = $sharetitle;
        $shareinfo['shareimgurl'] = $shareimgurl;
        $shareinfo['shareurl'] = $shareurl;
        return $shareinfo;
    }

    //判断客资收集表单
    static function get_open_other_form($system,$config)
    {
        if ($system['other_form']==1){
            return true;
        }
        if ($system['lottery']==1){//抽奖
            return true;
        }
        if ($system['ruanjian']==10){//微客
            return true;
        }
        if ($config['mystery_get_friend_info']==1){//盲盒开启收集客资
            return true;
        }
        if ($config['isicon']==3 && ($config['friendorder']==1 || $config['iconziliao']!=1)) { //邀请好友助力未报名
            return true;
        }
        //盲盒 未支付拆盲盒 开启客资收集
        if ($config['get_mystery_boxes']==2){
            return true;
        }
        if ($system['isform']==1 && $config['form_mode']>0){ //纯表单页
            return true;
        }
        return false;
    }

    //微客打赏回调
    static function weikepay($system,$order){
        global $_G, $_P;
        $themeid = $order['themeid'];
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/weike/core/model.php');
        \WeikeModel::giveGiftRecord($config,$order['id'],$themeid);
    }

    /**
     * Desc:根据团人数获取阶梯团礼品
     * Author:cbw
     * Email:17854288794@163.com
     * Time: 2023/7/31 14:08
     * @param $config
     * @param $tuan_num
     * @return string
     */
    static function formatStepTuanGift($config,$tuan_num)
    {
        $tmp_str = '';
        $tmp_num_arr = [];
        $step_mode = $config['step_tuan_gift_mode'];
        if ($config['tuan_tips'] && is_array($config['tuan_tips'])){
            foreach ($config['tuan_tips'] as $k => $val){
                if (!in_array($val['num'],$tmp_num_arr)){
                    if ($tuan_num>=$val['num']){
                        if ($step_mode==0){
                            $tmp_str = $val['name'];
                            array_push($tmp_num_arr,$val['num']);
                        }else{
                            array_push($tmp_num_arr,$val['num']);
                            $tmp_str .= $val['name'].';';
                        }
                    }
                }
            }
        }
        return $tmp_str;
    }

    /**
     * Desc:判断文本5多选分类下的产品是否可以显示
     * Author:cbw
     * Time: 2023/8/19 10:10
     * @param $config
     * @param $themeid
     * @param $item_id
     * @return bool
     */
    static function getFormFIveAndLimitBuyCanShowByItemId($config,$themeid,$item_id){
        $item_show = true;
        if ($config['form_five_qty']==1){
            $tmp_config_options =  $config['options'];
            foreach ($tmp_config_options as $k => $v){
                if ($v['list'] && count($v['list'])>1){
                    $tmp_v_list = $v['list'];
                    foreach ($tmp_v_list as $kk => $vv){
                        //查询产品的绑定购买记录数
                        $vv_id = $vv['id'];
                        if ($item_id==$vv_id){
                            $sql = " select count(*) as cnt from ".tablename(t_form_five_user_flag)." where themeid='$themeid' and form_item_id='$vv_id'";
                            $used_total = db_find($sql)['cnt'];
                            if ($used_total>=$vv['qty']){
                                $item_show = false;
                                break 2;
                            }
                        }
                    }
                }
            }
        }
        return $item_show;
    }

    //返回按钮
    static function btns($themeid,$system,$config){
        $mode_type = $system['isCommPoints']==1?'积分':'红包';
        $field = [
            'gsumall' => ['filed_type'=>'type','filed_code' =>-1,'name'=>'全部','num' => 0],
            'gsum0' => ['filed_type'=>'type','filed_code' =>0,'name'=>'一级分销','num' => 0],
            'gsum2' =>['filed_type'=>'type','filed_code' =>2,'name'=>'二级分销','num' => 0],
            'gsum3' =>['filed_type'=>'type','filed_code' =>3,'name'=>'三级分销','num' => 0],
            'gsum4' =>['filed_type'=>'type','filed_code' =>4,'name'=>'转发'.$mode_type,'num' => 0],
            'gsum5' =>['filed_type'=>'type','filed_code' =>5,'name'=>'阅读'.$mode_type,'num' => 0],
            'gsum6' =>['filed_type'=>'type','filed_code' =>6,'name'=>'员工提成','num' => 0],
            'gsum7' =>['filed_type'=>'type','filed_code' =>7,'name'=>'阅读'.$mode_type,'num' => 0],
            'gsum12' =>['filed_type'=>'type','filed_code' =>12,'name'=>'代理提成','num' => 0],
            'gsum8' =>['filed_type'=>'type','filed_code' =>8,'name'=>'补余款','num' => 0],
            'gsum15' =>['filed_type'=>'type','filed_code' =>15,'name'=>'额外补发','num' => 0],
            'gsum16' =>['filed_type'=>'type','filed_code' =>16,'name'=>'团长红包','num' => 0],
            'gsum9' =>['filed_type'=>'type','filed_code' =>9,'name'=>'单买','num' => 0],
            'wei_fee' =>['filed_type'=>'status','filed_code' =>0,'name'=>'未发放','num' => 0],
            'fa_fee' =>['filed_type'=>'status','filed_code' =>1,'name'=>'已发放','num' => 0],
            'lock_fee' =>['filed_type'=>'status','filed_code' =>5,'name'=>'已锁定','num' => 0],
        ];

        if(($config['hbopenfee1']>0 && $system['autored']==0 )|| $system['autored']==2){
            $field['gsum10'] =  ['filed_type'=>'type','filed_code' => 10,'name'=>'进入链接','num' => 0];
            $field['gsum11'] =  ['filed_type'=>'type','filed_code' => 11,'name'=>'自己报名','num' => 0];
            $field['gsum99'] =  ['filed_type'=>'type','filed_code' => 99,'name'=>'手工提现','num' => 0];
        }

        //默认展示数组 不管数据为不为0都阿婆展示
        $default_show = ['gsumall','gsum0','wei_fee','fa_fee'];
        $sql = "SELECT sum(case when  status = 1 then fee else 0 end) gsumall,    
                       sum(case when  type in (0,1)  and status  = 1 then fee else 0 end) gsum0,              
                       sum(case when  type = 2  and status  = 1 then fee else 0 end) gsum2,        
                       sum(case when  type = 3  and status  = 1 then fee else 0 end) gsum3,        
                       sum(case when  type = 4  and status  = 1 then fee else 0 end) gsum4,        
                       sum(case when  type = 5  and status  = 1 then fee else 0 end) gsum5,        
                       sum(case when  type = 6  and status  = 1 then fee else 0 end) gsum6,        
                       sum(case when  type = 7  and status  = 1 then fee else 0 end) gsum7,  
                       sum(case when  type = 12  and status  = 1 then fee else 0 end) gsum12,       
                       sum(case when  type = 8  and status  = 1 then fee else 0 end) gsum8,  
                       sum(case when  type = 15  and status  = 1 then fee else 0 end) gsum15,    
                       sum(case when  type = 10  and status  = 1 then fee else 0 end) gsum10,        
                       sum(case when  type = 11  and status  = 1 then fee else 0 end) gsum11,        
                       sum(case when  type = 99  and status  = 1 then fee else 0 end) gsum99,  
                       sum(case when  type = 9  and status  = 1 then fee else 0 end) gsum9,    
                       sum(case when status=0 then fee else 0 end)  wei_fee,
                       sum(case when status=1 then fee else 0 end)  fa_fee,
                       sum(case when status=5 then fee else 0 end)  lock_fee
                        FROM ". tablename ( t_comm )." WHERE themeid = '{$themeid}'  ";
        $data = db_find($sql);
        $array_info = [];
        foreach($data as $key => $val){
            if($field[$key]){
                if(in_array($key,$default_show)||$val>0) {   //是默认展示的直接添加到数组
                    $field[$key]['num'] = sprintf("%.2f", $val);
                    $array_info[] = $field[$key];
                }
            }
        }

        return $array_info;
    }

    static function fxLists($themeid,$system,$config){
        global $_G,$_P;
        extract(Record::getSearchTime());
        $hasNext = true;
        $condition = '1=1 ';
        $condition.= " and cm.addtime > '{$starttime}' and cm.addtime <= '{$endtime}' ";
        if(!isset($_P['status'])||$_P['status']===''){
            $status = -1;
        }else{
            $status = intval($_P['status']);
        }

        if($status >= 0){
            $condition.= " and cm.status = '{$status}'  ";
        }
        if(!isset($_P['type'])||$_P['type']===''){
            $type = -1;
        }else{
            $type = intval($_P['type']);
        }
        if($type >= 0){
            $condition.= " and cm.type = '{$type}'  ";
        }
        if(!empty($_P['key'])){
            $condition.= str_replace("workerid","cm.workerid",$_P['key']);
        }
        $condition .= ' and cm.themeid = ' . $themeid;

        $keyword = trim($_P['keyword']);
        if(!empty($keyword)){
            if (intval($keyword)>0 && strlen($_P['keyword'])!=11){
                $condition.= " and (cm.uid = '{$keyword}' or  cm.ordersn = '{$keyword}' )";
            }else{
                $condition.= " and (f.nickname like '%{$keyword}%' or f.username like '%{$keyword}%' or f.mobile like '%{$keyword}%' or d.username like '%{$keyword}%'  )";
            }
        }
        if (!empty($_P['recordid'])){
            $condition .= ' and cm.recordid='.$_P['recordid'];
        }

        $pageNumber = max ( 1, intval ($_P['page']));
        $pageSize = 20;
        //  $pageSize = Theme::CheckTime($system,$theme,'查看', $pageNumber);

        $total = (int)db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename (t_comm) . " as cm left join ".tablename(t_record)." as d on d.id = cm.recordid
                                                left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid 
                                                WHERE {$condition}");

        $max_page = ceil($total/$pageSize);
        if ($max_page<=$page){
            $hasNext = false;
        }

        $sql = "SELECT cm.id,cm.themeid,cm.uid,cm.recordid,cm.workerid,cm.type,cm.status,cm.msg,cm.addtime,cm.fee,cm.ip,cm.city,
                                   f.nickname,f.avatar,f.username as user ,f.mobile,d.username as form_username,d.mobile as form_mobile FROM ".tablename(t_comm)." as cm
                        left join ".tablename(t_record)." as d on d.id = cm.recordid
                        left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid
                        WHERE {$condition} order by cm.id desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;

        $list = db_select ($sql);
        foreach ($list as $index =>$row) {
            if (!empty($row['workerid'])) {
                $r = Worker::getWokerName($system, $themeid, $row['workerid'],$worklist);
                $list[$index]['workername'] = $r['workername'];
                $list[$index]['teamname'] = $r['teamname'];
                $list[$index]['companyname'] = $r['companyname'];
            }

            $list[$index]['addtime'] = date('Y-m-d H:i:s',$row['addtime']);
            //阅读红包
            if($row['type'] == 4 || $row['type'] == 7){
                $list[$index]['order_name'] = '地区';
                $list[$index]['recordid'] =  $row['ip'];
                $list[$index]['form_username'] =  $row['city'];
            }else{
                $list[$index]['order_name'] = '定单';
                if($row['recordid']){
                    $recordid = $row['recordid'] + 9000;
                }else{
                    $recordid = '';
                }
                $list[$index]['recordid'] = $recordid;
            }

            $type_name = Comm::getCommtypeName($row['type'],$system['isCommPoints']);
            $list[$index]['typename'] = $type_name;

            $msg = '';
            if($row['msg'] =='-2:openid与商户appid不匹配'){
                $msg = '近期未打开活动链接';
            }else {
                if ($row['status'] == 0) {
                    if ($system['send_mode'] == 1 && $row['addtime'] > time() - 60) {
                        $msg = '系统自动发放中，预计90秒到帐';
                    }
                }else if ($row['status']==5){
                    $msg = $row['msg'];
                }
            }
            $list[$index]['msg'] = $msg;

            $status_name = '';
            if($row['status']==0){
                if((($config['hbopenfee1']>0 && $system['autored']==0 )|| $system['autored']==2) && $row['type']!=99){
                    $status_name = '未提现';
                }else{
                    if( $system['isCommPoints']==1){

                    }else{
                        $status_name = '未发放';
                    }
                }
            }elseif($row['status']==99){
                $status_name = '已提现到账';
            }elseif($row['status']==30){
                $status_name = '发放中';
            }elseif($row['status']==5){
                $status_name = '已锁定';
            }else{
                $status_name = '已发放';
            }
            if($row['tiaozhuan']==1){
                $status_name .= '原后台发放';
            }

            //是否存在补发
            $list[$index]['status_name'] = $status_name;

            $list[$index]['bufa'] = 0;
            if($row['status']==0 || ($row['status']==5 and !($row['nickname'] == '新用户' || $row['nickname'] == '微信用户' || $row['nickname'] == '不在活动地区'))){
                if ($system['autored'] == 0 || ($system['autored'] < 2 || ($system['autored'] == 2 && $row['type'] == 99)) && $system['isCommPoints'] != 1 && $row['type'] != 10 && $row['type'] != 11) {
                    $list[$index]['bufa'] = 1;
                }
            }
        }
        $result['list'] = $list;
        $result['page'] = $pageNumber;
        $result['total'] = $total;
        $result['hasNext'] = $hasNext;
        return  $result;
    }
    //详情
    static function getInfo($themeid,$system){
        global $_G,$_P;
        $uid  = intval($_P['uid']);
        // $page = intval($_P['page']);
        $pageNumber = max ( 1, intval($page));
        //  $pageSize = 20;
        $condition = " cm.themeid={$themeid} and cm.uid = {$uid}";
        //    $hasNext = true;
        $total = (int)db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename (t_comm) . " as cm left join ".tablename(t_record)." as d on d.id = cm.recordid
                                                left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid 
                                                WHERE {$condition}");
//        $max_page = ceil($total/$pageSize);
//        if ($max_page<=$page){
//            $hasNext = false;
//        }
        $hasNext = false;
        $sql = "SELECT cm.id,cm.uid,cm.type,cm.fee,cm.recordid,cm.msg,cm.addtime,d.username as form_username,cm.ip,cm.city FROM ".tablename(t_comm)." as cm
                    left join ".tablename(t_record)." as d on d.id = cm.recordid
                    WHERE {$condition} order by cm.addtime desc";
        //     LIMIT ".($pageNumber - 1) * $pageSize . ',' . $pageSize

        $list = db_select($sql);

        foreach ($list as $index => $row){
            $list[$index]['addtime'] = date('y/m/d H:i:s',$row['addtime']);
            $list[$index]['fee'] = $row['fee']*1;
            $type_name = Comm::getCommtypeName($row['type'],$system['isCommPoints']);
            $list[$index]['typename'] = $type_name;
            if($row['type']==4||$row['type']==7){
                $list[$index]['form_username'] =$row['ip'].$row['city'];
            }
            if($row['msg']=='自动发放'||$row['msg']=='NULL'){
                $list[$index]['msg'] = '';
            }
        }
        $result['list'] = $list;
        $result['page'] = $pageNumber;
        $result['total'] = $total;
        $result['hasNext'] = $hasNext;
        return $result;
    }
    //点击补发
    static function checkFee($id,$themeid,$system){
        $comm = db_find ( "SELECT * FROM ".tablename(t_comm)." WHERE id ='{$id}'" );
        if ($system['autored']<2 || ($system['autored']==2 && $comm['type'] == 99)){
            $totalpayfee = Order::getRealByThemeIdnew($themeid)-$comm['fee'] ;
            if ($totalpayfee<-2){
                return_json(1,'您的余额不足,无法退款,需先充值再补发');
            }
            if ($system['autored']!=0  && ($comm['type']==10 || $comm['type']==11)) {
                return_json(1,'此类红包不可补发');
            }
            if ($system['send_mode']==1){
                $receiver = array(
                    'type'=>'PERSONAL_OPENID',
                    'account'=>$comm['openid'],
                    'relation_type'=>'STAFF',
                );
                $ret = Util::profitsharing_addreceiver($comm['uniacid'],$receiver,$system);
            }
            $r = Fee::commRecord($comm,$system);
            if($r[0]=="0"){
                return_json(0,'补发成功');
            }else{
                return_json(1,'补发失败');
            }
        }else{
            return_json(1,"无权操作");
        }
    }

    /**
     * Desc:判断九宫格抽奖的时间限制问题
     * Author:cbw
     * Time: 2023/9/23 13:34
     * @param $system
     * @param $config
     * @param $theme
     * @return bool
     */
    static function getLotteryLimitTime($system,$config,$theme)
    {
        if ($system['lottery']==1 ){
            if ($config['is_limit_end_time']){//启用抽奖限制
                if (TIMESTAMP < $config['yx_lt_endtime'] && TIMESTAMP > $config['yx_lt_begintime']){
                    return true;
                }
            }else{
                if (TIMESTAMP > $theme['begintime'] && TIMESTAMP < $theme['endtime']){
                    return true;
                }
            }
        }
        return false;
    }
}